import 'dart:math';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:yi_shop/model/attention.dart';
import 'package:yi_shop/model/product.dart';
import 'package:yi_shop/model/store.dart';
import 'package:yi_shop/ui/scroll_refresh_config.dart';
import 'package:yi_shop/utils/colors.dart';
import 'package:yi_shop/utils/styles.dart';
import 'package:yi_shop/utils/svg.dart';

class AttentionProductController extends GetxController {
  RxList<NewProductModel> pageList = RxList([]);

  RefreshController refreshController = RefreshController();

  @override
  void onInit() {
    pageList.add(NewProductModel(
        name: '平底包头凉鞋女夏季新款网红女鞋韩版百搭后空一字带',
        imgUrl:
            'https://m.360buyimg.com/n6/jfs/t1/167275/34/40038/156033/661f3bd9F948d82bd/1cf12d8310c0a2c5.jpg!q70.dpg',
        price: 34));
    initData();
    super.onInit();
  }

  Future<void> onRefresh() async {
    /// 发起请求
    await Future.delayed(const Duration(milliseconds: 2000));
    refreshController.refreshCompleted(resetFooterState: true);
  }

  Future<void> onLoading() async {
    /// 发起请求
    await Future.delayed(const Duration(milliseconds: 2000));

    /// if failed, use loadFailed(), if no data return, use LoadNodata()
    if (pageList.length > 32) {
      return refreshController.loadNoData();
    }

    /// 添加数据
    initData();

    /// 完毕
    refreshController.loadComplete();
  }

  void initData() {
    var r = Random.secure();
    for (var i = 0; i < 10; i++) {
      pageList.add(NewProductModel(
          name: '平底包头凉鞋女夏季新款网红女鞋韩版百搭后空一字带',
          imgUrl:
              'https://m.360buyimg.com/n6/jfs/t1/167275/34/40038/156033/661f3bd9F948d82bd/1cf12d8310c0a2c5.jpg!q70.dpg',
          price: r.nextInt(300)));
    }
  }
}

class AttentionProductView extends GetView<AttentionProductController> {
  const AttentionProductView({super.key});

  @override
  Widget build(BuildContext context) {
    return Obx(() => scrollRefreshConfig(context));
  }

  ScrollRefreshConfig scrollRefreshConfig(BuildContext context) {
    return ScrollRefreshConfig(
      refreshController: controller.refreshController,
      onRefresh: controller.onRefresh,
      onLoading: controller.onLoading,
      child: listViewBuilder(context),
    );
  }

  ListView listViewBuilder(BuildContext context) {
    return ListView.builder(
      itemBuilder: (_, int index) {
        var row = controller.pageList[index];
        return Container(
          height: 165,
          margin: EdgeInsets.only(top: index == 0 ? 20 : 10),
          padding: const EdgeInsets.only(top: 10, left: 15, right: 15, bottom: 0),
          decoration: const BoxDecoration(color: Colors.white),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.start,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              ClipRRect(
                borderRadius: BorderRadius.circular(5),
                child: CachedNetworkImage(
                  imageUrl: row.imgUrl,
                  width: 90,
                  height: 90,
                  fit: BoxFit.fill,
                ),
              ),
              Expanded(
                  child: Container(
                padding: const EdgeInsets.only(left: 10),
                alignment: Alignment.centerLeft,
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Container(
                      alignment: Alignment.centerLeft,
                      child: Text(
                        row.name,
                        style: StylesUtils.customTextStyle(
                            color: ColorsUtils.color3333,
                            fontSize: StylesUtils.fontSize13,
                            lineHeight: 1.3.h),
                        maxLines: 2,
                        overflow: TextOverflow.ellipsis,
                      ),
                    ),
                    Container(
                      margin: const EdgeInsets.only(bottom: 10, top: 15),
                      alignment: Alignment.centerLeft,
                      child: Text(
                        '￥${row.price}.00',
                        style: StylesUtils.customTextStyle(
                          color: ColorsUtils.colorEc80,
                        ),
                      ),
                    ),
                    Wrap(
                      crossAxisAlignment: WrapCrossAlignment.center,
                      alignment: WrapAlignment.start,
                      spacing: 25,
                      children: [
                        TextButton(
                            onPressed: () {},
                            style: ButtonStyle(
                                fixedSize: const MaterialStatePropertyAll(Size(60, 24)),
                                minimumSize: const MaterialStatePropertyAll(Size(60, 24)),
                                padding: const MaterialStatePropertyAll(EdgeInsets.zero),
                                alignment: Alignment.center,
                                shape: MaterialStatePropertyAll(RoundedRectangleBorder(
                                    borderRadius: BorderRadius.circular(5.r),
                                    side: BorderSide(
                                        color: ColorsUtils.parseColorFromHexString(
                                            ColorsUtils.color7979))))),
                            child: Text(
                              '看相似',
                              style: StylesUtils.customTextStyle(
                                  color: ColorsUtils.color3333, fontSize: StylesUtils.fontSize13),
                            )),
                        TextButton(
                            onPressed: () {},
                            style: ButtonStyle(
                                fixedSize: const MaterialStatePropertyAll(Size(80, 24)),
                                minimumSize: const MaterialStatePropertyAll(Size(80, 24)),
                                padding: const MaterialStatePropertyAll(EdgeInsets.zero),
                                alignment: Alignment.center,
                                shape: MaterialStatePropertyAll(RoundedRectangleBorder(
                                    borderRadius: BorderRadius.circular(5.r),
                                    side: BorderSide(
                                        color: ColorsUtils.parseColorFromHexString(
                                            ColorsUtils.color7979))))),
                            child: Text(
                              '降价通知',
                              style: StylesUtils.customTextStyle(
                                  color: ColorsUtils.color3333, fontSize: StylesUtils.fontSize13),
                            )),
                        Container(
                          width: 40,
                          alignment: Alignment.center,
                          child: InkWell(
                              onTap: () {},
                              child: SvgUtils.assetName('u14460', width: 30, height: 25)),
                        )
                      ],
                    )
                  ],
                ),
              ))
            ],
          ),
        );
      },
      itemCount: controller.pageList.length,
      itemExtent: 165,
    );
  }
}

class AttentionStoreController extends GetxController {
  RxList<StoreAttentionModel> pageList = RxList([]);

  RefreshController refreshController = RefreshController();

  @override
  void onInit() {
    pageList.add(StoreAttentionModel(
        name: '坐标轴旗舰店',
        imgUrl:
            'https://img10.360buyimg.com/n2/s240x240_jfs/t1/145616/28/35917/157951/64bb34ccF5d8c73bd/1bde653220fd190a.jpg!q70.jpg.webp',
        attention: 20,
        news: 34));
    initData();
    super.onInit();
  }

  Future<void> onRefresh() async {
    /// 发起请求
    await Future.delayed(const Duration(milliseconds: 2000));
    refreshController.refreshCompleted(resetFooterState: true);
  }

  Future<void> onLoading() async {
    /// 发起请求
    await Future.delayed(const Duration(milliseconds: 2000));

    /// if failed, use loadFailed(), if no data return, use LoadNodata()
    if (pageList.length > 32) {
      return refreshController.loadNoData();
    }

    /// 添加数据
    initData();

    /// 完毕
    refreshController.loadComplete();
  }

  void initData() {
    var r = Random.secure();
    for (var i = 0; i < 10; i++) {
      pageList.add(StoreAttentionModel(
          name: '坐标轴旗舰店',
          imgUrl:
              'https://img11.360buyimg.com/n2/s240x240_jfs/t1/195076/2/44147/192873/661cfbaaF9c9a0613/8ff925f3a951e082.png!q70.jpg.webp',
          news: r.nextInt(30),
          attention: r.nextInt(50)));
    }
  }
}

class AttentionStoreView extends GetView<AttentionStoreController> {
  const AttentionStoreView({super.key});

  @override
  Widget build(BuildContext context) {
    return Obx(() => scrollRefreshConfig(context));
  }

  ScrollRefreshConfig scrollRefreshConfig(BuildContext context) {
    return ScrollRefreshConfig(
      refreshController: controller.refreshController,
      onRefresh: controller.onRefresh,
      onLoading: controller.onLoading,
      child: listViewBuilder(context),
    );
  }

  ListView listViewBuilder(BuildContext context) {
    return ListView.builder(
      itemBuilder: (_, int index) {
        var row = controller.pageList[index];
        return Container(
          height: 90,
          margin: EdgeInsets.only(top: index == 0 ? 20 : 10),
          padding: const EdgeInsets.symmetric(vertical: 15, horizontal: 20),
          decoration: const BoxDecoration(color: Colors.white),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.start,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              CircleAvatar(
                radius: 25,
                backgroundImage: CachedNetworkImageProvider(
                  row.imgUrl,
                ),
              ),
              Expanded(
                  child: Container(
                padding: const EdgeInsets.only(left: 10),
                child: Column(
                  children: [
                    Container(
                      alignment: Alignment.centerLeft,
                      child: Text(
                        row.name,
                        style: StylesUtils.customTextStyle(color: ColorsUtils.color3333),
                      ),
                    ),
                    Container(
                      alignment: Alignment.centerLeft,
                      margin: const EdgeInsets.only(top: 10),
                      child: Text(
                        '${row.attention}+万人关注',
                        style: StylesUtils.customTextStyle(
                            color: ColorsUtils.color9999, fontSize: StylesUtils.fontSize13),
                      ),
                    )
                  ],
                ),
              )),
              Center(
                child: Text(
                  '上新+${row.news}',
                  style: StylesUtils.customTextStyle(color: ColorsUtils.colorF048),
                ),
              )
            ],
          ),
        );
      },
      itemCount: controller.pageList.length,
      itemExtent: 90,
    );
  }
}

class AttentionExpertController extends GetxController {
  RxList<Rx<AttentionExpertModel>> pageList = RxList([]);

  RefreshController refreshController = RefreshController();

  @override
  void onInit() {
    pageList.add(Rx(AttentionExpertModel(
        nickname: '如意家—每日上新',
        avatar:
            'https://img2.baidu.com/it/u=2654102281,3004956653&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=501',
        fans: 4599)));
    initData();
    super.onInit();
  }

  Future<void> onRefresh() async {
    /// 发起请求
    await Future.delayed(const Duration(milliseconds: 2000));
    refreshController.refreshCompleted(resetFooterState: true);
  }

  Future<void> onLoading() async {
    /// 发起请求
    await Future.delayed(const Duration(milliseconds: 2000));

    /// if failed, use loadFailed(), if no data return, use LoadNodata()
    if (pageList.length > 32) {
      return refreshController.loadNoData();
    }

    /// 添加数据
    initData();

    /// 完毕
    refreshController.loadComplete();
  }

  void initData() {
    var r = Random.secure();
    for (var i = 0; i < 10; i++) {
      pageList.add(Rx(AttentionExpertModel(
          nickname: '如意家—每日上新',
          avatar:
              'https://img0.baidu.com/it/u=3547779937,694625124&fm=253&fmt=auto&app=138&f=JPEG?w=285&h=285',
          fans: r.nextInt(99999))));
    }
  }
}

class AttentionExpertView extends GetView<AttentionExpertController> {
  const AttentionExpertView({super.key});

  @override
  Widget build(BuildContext context) {
    return Obx(() => scrollRefreshConfig(context));
  }

  ScrollRefreshConfig scrollRefreshConfig(BuildContext context) {
    return ScrollRefreshConfig(
      refreshController: controller.refreshController,
      onRefresh: controller.onRefresh,
      onLoading: controller.onLoading,
      child: listViewBuilder(context),
    );
  }

  ListView listViewBuilder(BuildContext context) {
    return ListView.builder(
      itemBuilder: (_, int index) {
        var row = controller.pageList[index];
        return Container(
          height: 90,
          margin: EdgeInsets.only(top: index == 0 ? 20 : 10),
          padding: const EdgeInsets.symmetric(vertical: 15, horizontal: 20),
          decoration: const BoxDecoration(color: Colors.white),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.start,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              CircleAvatar(
                radius: 25,
                backgroundImage: CachedNetworkImageProvider(
                  row.value.avatar,
                ),
              ),
              Expanded(
                  child: Container(
                padding: const EdgeInsets.only(left: 10),
                child: Column(
                  children: [
                    Container(
                      alignment: Alignment.centerLeft,
                      child: Text(
                        row.value.nickname,
                        style: StylesUtils.customTextStyle(color: ColorsUtils.color3333),
                      ),
                    ),
                    Container(
                      alignment: Alignment.centerLeft,
                      margin: const EdgeInsets.only(top: 10),
                      child: Text(
                        '粉丝 ${row.value.fans}',
                        style: StylesUtils.customTextStyle(
                            color: ColorsUtils.color9999, fontSize: StylesUtils.fontSize13),
                      ),
                    )
                  ],
                ),
              )),
              Center(
                child: Obx(() => TextButton(
                    onPressed: () {
                      row.update((val) {
                        val?.checked = !val.checked;
                      });
                    },
                    style: ButtonStyle(
                        alignment: Alignment.center,
                        backgroundColor: MaterialStatePropertyAll(row.value.checked
                            ? ColorsUtils.parseColorFromHexString(ColorsUtils.colorF048)
                            : Colors.transparent),
                        padding: const MaterialStatePropertyAll(EdgeInsets.zero),
                        minimumSize: const MaterialStatePropertyAll(Size(80, 30)),
                        fixedSize: const MaterialStatePropertyAll(Size(80, 30)),
                        shape: MaterialStatePropertyAll(RoundedRectangleBorder(
                            side: BorderSide(
                                width: row.value.checked ? 0 : 1,
                                color: ColorsUtils.parseColorFromHexString(ColorsUtils.colorF048)),
                            borderRadius: BorderRadius.circular(5.r)))),
                    child: Text(
                      row.value.checked ? '关注' : '已关注',
                      style: StylesUtils.customTextStyle(
                          color: row.value.checked ? ColorsUtils.colorFfff : ColorsUtils.colorF048),
                    ))),
              )
            ],
          ),
        );
      },
      itemCount: controller.pageList.length,
      itemExtent: 90,
    );
  }
}
